package solutionsdemo;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 黎鹤舞
 * Date: 2024-01-29
 * Time: 14:53
 */

import java.util.LinkedList;
import java.util.Queue;

/**
 * 判断是否为完全二叉树:
 * 通过队列进行层序遍历，如果遍历到了Null，但是队列中仍有元素存在，return false;
 */
public class CompleteBinaryTree {
    public boolean completeTree(TreeNode root) {
        if(root == null) {
            return true;
        }
        //需要建立一个
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while(queue.peek() != null) {
            TreeNode temp = queue.poll();
            queue.offer(temp.left);
            queue.offer(temp.right);
        }
        //此时栈顶元素为null
        while (!queue.isEmpty()) {
            queue.poll();
            if(queue.peek() != null) {
                return false;
            }
        }
        return true;
    }
}
